<template>
  <view class="container padding-bottom-80">
    <view style="margin-top: 120rpx;"></view>
    <!-- 使用通用导航栏组件 -->
    <nav-bar :title="formData.package_id ? '编辑卡包' : '新增卡包'" />
    
    <uni-forms ref="form" :model="formData" :rules="rules">
      <uni-forms-item label="卡包名称" name="name" required>
        <uni-easyinput v-model="formData.name" placeholder="请输入卡包名称" />
      </uni-forms-item>
      
      <!-- 编辑默认卡包时不显示卡包类型 -->
      <uni-forms-item v-if="!isDefaultCardPackage" label="卡包类型" name="card_type" required>
        <uni-group>
          <view class="card-type-container">
            <view 
              v-for="type in cardTypes" 
              :key="type.value"
              class="card-type-item"
              :class="{ selected: formData.card_type === type.value }"
              @click="formData.card_type = type.value"
            >
              <text>{{ type.text }}</text>
              <uni-icons 
                :type="formData.card_type === type.value ? 'checkbox-filled' : 'checkbox'" 
                :color="formData.card_type === type.value ? '#4cd964' : '#999'" 
                size="20"
              />
            </view>
          </view>
        </uni-group>
      </uni-forms-item>
      
      <!-- 非次卡时显示充值金额、赠送金额和总金额 -->
      <uni-forms-item label="充值金额" name="recharge_amount" required>
          <uni-easyinput 
            v-model="formData.recharge_amount" 
            type="number" 
            placeholder="请输入充值金额"
            @input="updateTotalAmount"
          />
        </uni-forms-item>
      <template v-if="formData.card_type !== 'per_use'">
        <uni-forms-item label="赠送金额" name="gift_amount" required>
          <uni-easyinput 
            v-model="formData.gift_amount" 
            type="number" 
            placeholder="请输入赠送金额"
            @input="updateTotalAmount"
          />
        </uni-forms-item>

        <uni-forms-item label="总金额" name="total_amount">
          <uni-easyinput 
            :value="computedTotalAmount" 
            type="number" 
            placeholder="自动计算"
            disabled
          />
        </uni-forms-item>
      </template>
      
      <!-- 次卡时直接显示总次数 -->
      <template v-else>
        <uni-forms-item label="总次数" name="total_amount" required>
          <uni-easyinput 
            v-model="formData.total_amount" 
            type="number" 
            placeholder="请输入总次数"
          />
        </uni-forms-item>
      </template>
      <uni-forms-item label="卡销售提成比例" name="commission_rate" required>
        <view style="display: flex; align-items: center;">
          <uni-easyinput 
            v-model="formData.commission_rate" 
            type="number" 
            placeholder="请输入此卡销售的提成比例"
            style="flex: 1;"
          />
          <text style="margin-left: 10rpx;">%</text>
        </view>
        
      </uni-forms-item>
      <uni-forms-item>
        <view class="flex-center">
          <text style="margin-left: 10rpx;color: red;">
          销售提成比例修改会同步到所有当前店铺的此卡中，所有业务新销售的此卡都会同步提成比例。
        </text></view>
      </uni-forms-item>
      
      <!-- 非次卡时显示几折卡 -->
      <template v-if="formData.card_type !== 'per_use'">
      <uni-forms-item label="客户消费打折" name="discount_rate" required>
        <view style="display: flex; align-items: center;">
          <uni-easyinput 
            v-model="formData.discount_rate" 
            type="number" 
            placeholder="请输入客户消费打折,如理发"
            style="flex: 1;"
          />
          <text style="margin-left: 10rpx;">折</text>
        </view>
      </uni-forms-item>
      </template>
      <uni-forms-item label="有效期" name="expiry_date">
        <uni-datetime-picker 
          type="date" 
          v-model="formData.expiry_date" 
          placeholder="请选择有效期"
        />
      </uni-forms-item>
      <button type="primary" @click="submitForm">保存</button>
    </uni-forms>
  </view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue';
import cardPackage from '@/utils/card_package.js';
import Util from '@/utils/util.js';

export default {
  components: {
    NavBar
  },
  data() {
    return {
      formData: {
        package_id: '',       // 卡包ID
        name: '',             // 卡包名称
        card_type: 'comprehensive', // 卡包类型(综合卡/次卡)
        recharge_amount: '',  // 充值金额(用户实际支付的金额)
        gift_amount: '',       // 赠送金额(商家额外赠送的金额)
        total_amount: '',      // 总金额(充值金额+赠送金额)
        expiry_date: '',       // 有效期
        commission_rate: 0,    // 销售提成比例(百分比)
        discount_rate: 0,     // 客户销售比例(百分比)
        store_id: ''           // 所属店铺ID
      },
      cardTypes: [
        { value: 'comprehensive', text: '综合卡' },
        { value: 'per_use', text: '次卡' }
      ],
      rules: {
        name: {
          rules: [{
            required: true,
            errorMessage: '请输入卡包名称'
          }]
        },
        recharge_amount: {
          rules: [{
            required: true,
            errorMessage: '请输入充值金额',
            validateFunction: (rule, value, data, callback) => {
              return new Promise((resolve, reject) => {
                const num = Number(value);
                if (isNaN(num)) {
                  reject('请输入有效数字');
                } else if (num < 0) {
                  reject('充值金额不能为负数');
                } else {
                  resolve();
                }
              });
            }
          }]
        },
        card_type: {
          rules: [{
            required: true,
            errorMessage: '请选择卡包类型'
          }]
        },
        // 修改验证规则
        commission_rate: {
          rules: [{
            required: true,
            errorMessage: '请输入销售提成比例',
            validateFunction: (rule, value, data, callback) => {
              return new Promise((resolve, reject) => {
                const num = Number(value);
                if (isNaN(num)) {
                  reject('请输入有效数字');
                } else if (num < 0 || num > 100) {
                  reject('提成比例必须在0-100之间');
                } else {
                  resolve();
                }
              });
            }
          }]
        },
        discount_rate: {
          rules: [{
            required: true,
            errorMessage: '请输入客户打折',
            validateFunction: (rule, value, data, callback) => {
              return new Promise((resolve, reject) => {
                const num = Number(value);
                if (isNaN(num)) {
                  reject('请输入有效数字');
                } else if (num < 1 || num > 10) {
                  reject('打折必须在1-10之间');
                } else if (!/^\d+(\.\d{0,1})?$/.test(value)) {
                  reject('最多只能有一位小数');
                } else {
                  resolve();
                }
              });
            }
          }]
        }
      }
    };
  },
  onLoad(options) {
    this.formData.store_id = options.store_id || '';
    this.formData.package_id = options.package_id || '';
    if (options.package_id) {
      this.loadCardPackage(options.package_id);
    } else {
      this.formData.remaining_amount = this.formData.total_amount;
    }
  },
  computed: {
    isDefaultCardPackage() {
      return this.formData.package_id && this.formData.card_type === 'default';
    },
    computedTotalAmount() {
      if (this.formData.card_type !== 'per_use') {
        const recharge = Number(this.formData.recharge_amount) || 0;
        const gift = Number(this.formData.gift_amount) || 0;
        return (recharge + gift).toFixed(2);
      }
      return this.formData.total_amount;
    }
  },
  methods: {
    updateTotalAmount() {
      this.formData.total_amount = this.computedTotalAmount;
    },
    async submitForm() {
      try {
        // 根据卡包类型动态设置验证规则
        if (this.formData.card_type === 'per_use') {
          this.rules.total_amount = {
            rules: [{ required: true, errorMessage: '请输入总次数' }]
          };
        } else {
          this.rules.total_amount = {
            rules: [{ required: true, errorMessage: '请输入总金额' }]
          };
          // 确保总金额正确计算
          this.formData.total_amount = this.computedTotalAmount;
          this.rules.discount_rate = {
                rules: [{
                required: true,
                errorMessage: '请输入客户打折',
                validateFunction: (rule, value, data, callback) => {
                        return new Promise((resolve, reject) => {
                        const num = Number(value);
                        if (isNaN(num)) {
                            reject('请输入有效数字');
                        } else if (num < 0 || num > 100) {
                            reject('打折必须在0-100之间');
                        } else {
                            resolve();
                        }
                        });
                }
                }]
            };
        }

        

        await this.$refs.form.validate();
        
        const params = {
          ...this.formData,
          total_amount: parseFloat(this.formData.total_amount),
          commission_rate: this.formData.commission_rate / 100,
          discount_rate: (this.formData.discount_rate / 10).toFixed(2) // 转换为两位小数
        };
        
        if (this.formData.package_id) {
          await cardPackage.update(this.formData.package_id, params);
          uni.showToast({ title: '更新成功', icon: 'success' });
        } else {
          await cardPackage.create(params);
          uni.showToast({ title: '新增成功', icon: 'success' });
        }
        
        uni.$emit('refreshCardPackageList');
        uni.navigateBack();
      } catch (error) {
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        });
      }
    },
    // 加载卡包数据时转换小数到百分比
    async loadCardPackage(packageId) {
      try {
        const res = await cardPackage.getById(packageId);
        this.formData = {
          ...res,
          expiry_date: Util.formatDate(res.expiry_date),
          commission_rate: Math.round(res.commission_rate * 100),
          discount_rate: (res.discount_rate * 10).toFixed(1) // 转换为一位小数
        };
      } catch (error) {
        console.error(error);
        uni.showToast({
          title: '加载卡包信息失败',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style>
.container {
  padding: 0 30rpx;
  background-color: #f5f5f5;
}

uni-forms {
  margin: 0 -30rpx;
  padding: 20rpx 30rpx;
  background-color: #fff;
}

/* 添加以下样式 */
.card-type-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin: 0 -10rpx;
}

.card-type-item {
  display: flex;
  align-items: center;
  padding: 15rpx 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  margin-right: 15rpx;
  margin-bottom: 15rpx;
  background-color: #fff;
}

.card-type-item.selected {
  background-color: #4cd964;
  border-color: #4cd964;
  color: white;
}

.card-type-item.selected .uni-icons {
  color: white;
  border: 1rpx solid white;
  border-radius: 50%;
}
</style>